package com.thinkgem.jeesite.modules.sys.helper.sysinittask;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.modules.sys.entity.RegularTask;
import com.thinkgem.jeesite.modules.sys.helper.timertask.AbstractRegularTimeTask;
import com.thinkgem.jeesite.modules.sys.service.RegularTaskService;

public class RegularTaskInitTask implements ISysInitTask{

	@Autowired
	private RegularTaskService regularTaskService;
	
	@Override
	public String onSysInit(ServletContext ctx, WebApplicationContext springContext) {
		ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
		List<RegularTask> regularTasks = regularTaskService.findList(null);
		try{
			if(regularTasks!=null && regularTasks.size()>0){
				for(RegularTask regularTask: regularTasks){
					Class<?> taskClazz = Class.forName(regularTask.getTaskPath());
					AbstractRegularTimeTask regularExecuteTask = (AbstractRegularTimeTask) taskClazz.newInstance();
					pool.schedule(regularExecuteTask,  Long.parseLong(regularTask.getRunTime()), TimeUnit.MILLISECONDS);
					//pool.scheduleWithFixedDelay(command, initialDelay, delay, unit)
				}
			}
		}catch (Exception e){
			System.out.println("==================定时任务发生错误==============");
		}
		return Global.TRUE;
	}

	@Override
	public void onSysDestroy(ServletContext servletContext, WebApplicationContext springContext) {
		
	}

}
